#pragma once

#include <QObject>
#include <QTcpServer>
#include "rtsp.h"
#include "RtspConnection.h"
#include <unordered_map>


namespace jlh {
	struct ServerFrame {
		MediaSessionId sessionId = 0;
		MediaChannelId channelId;
		AVFrame frame;
	};

}
namespace jlh {

	class RtspServerWorker : public QObject, public Rtsp
	{
		Q_OBJECT

	public:
		explicit RtspServerWorker(QObject *parent=nullptr);
		virtual ~RtspServerWorker();

		void Start(const char* ip, uint16_t port);
		void Stop();

		MediaSessionId AddSession(MediaSession* session);
		void RemoveSession(MediaSessionId sessionId);

		MediaSessionPtr LookMediaSession(const std::string& suffix) override;
		MediaSessionPtr LookMediaSession(MediaSessionId sessionId) override;

		bool PushFrame(MediaSessionId sessionId, MediaChannelId channelId, AVFrame& frame);

	signals:
		void sstart();
		void sstop();
		void sFrame();

	protected slots:
		void ostart();
		void ostop();
		void onConnect();
		void onFrame();

	private:
		std::string ip_ = "0.0.0.0";
		uint16_t port_ = 554;
		std::shared_ptr<QTcpServer> rtsp_server_;

		std::mutex mutex_;
		std::vector<std::shared_ptr<RtspConnection>> rtsp_clients_;
		std::unordered_map<std::string, MediaSessionId> rtsp_suffix_map_;
		std::unordered_map<MediaSessionId, std::shared_ptr<MediaSession>> media_sessions_;

		std::list<ServerFrame> frames_;
	};

}